<template>
  <div class="ts-info" ref="tsInfo">
    <ts-header class="ts-header" title="个人信息" custom @onBack="onBack">
      <span slot="right" @click="updMode">{{mode === 'edit' ? '保存' : '编辑'}}</span>
    </ts-header>
    <flex-view>
      <div>
        <div v-if="info.is_status!==2" class="pending" :class="{'checking':isChecking(),'faild':isFaild()}"
             @click="readReason">
          <span v-if="isChecking()">审核中</span>
          <span v-if="isFaild()">审核信息未通过，请点击查看原因</span>
        </div>
        <div class="profile-container">
          <input ref="uload" v-if="!prod" type="file" id="upload" style="position:absolute; clip:rect(0 0 0 0);"
                 accept="image/png, image/jpeg, image/gif, image/jpg" @change="changeAvatar($event)">

          <section class="avator">
            <img v-if="cropAvatar" @click="upload2" class="pic" :src="cropAvatar"/>
            <svg class="pic" v-else @click="upload2">
              <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#avatar-default"></use>
            </svg>
            <!-- 线上 -->
            <label v-if="prod" class="update" @click="upload2" v-show="mode==='edit'">点击修改</label>
            <label v-else class="update" for="upload"  v-show="mode==='edit'">点击修改</label>
          </section>
          <edit-profile v-model="info" :mode="mode"></edit-profile>
          <ts-group>
          <uploader class="upd-over" :off="show" title="身份证正面" :required="false" :updTips="text" v-model="info.identity_behind"
                    @deleteImg="deleteImg"
                    :chose="chose"
                    @loadImageUpload="upload">
          </uploader>
          <uploader class="upd-over" :off="show" title="身份证反面" :updTips="text"  v-model="info.identity_front"
                    :required="false"
                    :chose="chose"
                    @deleteImg="deleteImg1"
                    @loadImageUpload="upload1">

          </uploader>
          </ts-group>
        </div>
      </div>
    </flex-view>
    <transition name="slide-child">
      <router-view class="child-route" @cropFinish="cropFinish"></router-view>
    </transition>
    <mt-actionsheet :actions="actions" v-model="sheetVisible"></mt-actionsheet>
    <mt-actionsheet :actions="actions1" v-model="sheetVisible1"></mt-actionsheet>
    <mt-actionsheet :actions="actions2" v-model="sheetVisible2"></mt-actionsheet>
  </div>
</template>

<script>
  import editProfile from '../../../components/module/EditProfile.vue'
  import {GET_PERSONAL_INFO, EDIT_PERSONAL_INFO} from '../../../assets/js/api'
  import transfer from '../../../core/transfer'
  import verify from '../../../utils/verify'
  import {SET_USER} from '../../../store/mutations-types'
  import {Actionsheet} from 'mint-ui';
  import {mapGetters} from 'vuex'
  import Loading from '../../../components/tsui/loading'

  let components = {
    editProfile
  };
  components[Actionsheet.name] = Actionsheet;
  export default {
    name: 'info',
    components: components,
    data() {
      return {
        cropAvatar: '',
        prod: window.$prod,
        info: {
          name: '',
          sex: null,
          birthday: '',
          province: null,
          city: null,
          county: null,
          other_name: '',
          other_tel: null,
          company_id: null,
          company_name: '',
          native_place: '',
          is_status: null,
          image: null,
          identity_front: [],
          identity_behind: []
        },
        mode: 'readonly',
        sheetVisible: false,
        sheetVisible1: false,
        sheetVisible2: false,
        cont: null,
        actions: [{
          name: '拍照',
          method: this.loadImageUpload_photograph
        }, {
          name: '从相册选择',
          method: this.loadImageUpload_album
        }],
        actions1: [{
          name: '拍照',
          method: this.loadImageUpload_photograph1
        }, {
          name: '从相册选择',
          method: this.loadImageUpload_album1
        }],
        actions2: [{
          name: '拍照',
          method: this.changeAvatar_info
        }, {
          name: '从相册选择',
          method: this.changeAvatar
        }]
      }
    },
    async activated() {
      let json = await this.$http.post(GET_PERSONAL_INFO);
      if (json.result === 1) {
        for (let item of Object.keys(json.data)) {
          if (item === 'is_status') {
            continue
          }
          this.info.is_status = json.data.is_status;
        }
      }
//      transfer.$once('currBack', () => {
//        this.onBack();
//      });
    },
    async created() {
      this.getInfo();
    },
    methods: {
      onBack() {
        //只有在编辑状态下提示保存信息
        if (this.mode === 'edit') {
          this.$modal({message: '是否保存信息', cancel: true}).then(action => {
            this.updMode();
            this.$router.goBack();
          }).catch(error => {
            this.getInfo();
            this.$router.goBack();
          })
        } else {
          this.$router.goBack();
        }

      },
      async getInfo() {
        let json = await this.$http.post(GET_PERSONAL_INFO);
        console.log(json)
        if (json.result === 1) {
          for (let item of Object.keys(json.data)) {
            if (item === 'identity_behind' || item === 'identity_front') {
              continue
            }
            this.$set(this.info, item, json.data[item])
          }
          this.info.identity_behind.length = 0;
          this.info.identity_front.length = 0;
          json.data.identity_behind.forEach((item) => {
            this.info.identity_behind.push(item)
          }, this);
          json.data.identity_front.forEach((item) => {
            this.info.identity_front.push(item)
          }, this);
          this.cropAvatar = this.info.image;
          this.$store.commit(SET_USER, {image: this.cropAvatar})
        }
      },
      cropFinish(cropAvatar) {
        this.info.image = cropAvatar.replace('data:image/jpeg;base64,', '');
        this.cropAvatar = cropAvatar;
      },
      async updMode() {
        if (this.mode === 'readonly') {
          this.mode = 'edit';
        } else {
          if (this.validName('name') && this.validName('other_name')) {
            console.log(this.info)
            let json = await this.$http.post(EDIT_PERSONAL_INFO, this.info, {show: true});
            console.log(json)
            if (json.result === 1) {
              this.$toast('修改成功');
              if (this.info.image !== json.data.image) {
                this.info.image = json.data.image;
                this.cropAvatar = this.info.image;
                this.$store.commit(SET_USER, {image: this.cropAvatar})
              }
              this.mode = 'readonly';
              this.info.is_status = 1;
            }
          }
        }
      },
      readReason() {
        if (this.info.is_status === 1) {
          return;
        }
        this.$router.push({path: '/profile/info/checkBack'});
      },
      upload() {
        if (this.mode === 'edit') {
          this.sheetVisible = !this.sheetVisible
        }
      },
      upload1() {
        if (this.mode === 'edit') {
          this.sheetVisible1 = !this.sheetVisible1
        }
      },
      upload2(){
        if (this.mode === 'edit') {
          this.sheetVisible2 = !this.sheetVisible2
        }
      },
      //上传头像
      changeAvatar(e) {
        if (this.mode === 'edit') {
          if ($prod) {
            let onCameraSuccess = (noCropAvatar) => {
              Loading.close();
              this.$router.replace({
                name: 'avatarCrop',
                params: {noCropAvatar: `data:image/jpeg;base64,${noCropAvatar}`}
              });
            };
            let onCameraError = (message) => {
              Loading.close();
            };
            navigator.camera.getPicture(onCameraSuccess, onCameraError, {
              //质量
              quality: 100,
              //不允许编辑
              allowEdit: false,
              //获取图片转为base64
              destinationType: Camera.DestinationType.DATA_URL,
              //编码类型JPEG
              encodingType: Camera.EncodingType.JPEG,
              //只允许图片
              mediaType: Camera.MediaType.PICTURE,
              //类型是选择图片
              sourceType: Camera.PictureSourceType.SAVEDPHOTOALBUM,
              targetWidth: 375
            });
            Loading.open()
          }
          else {
            //上传头像
            console.log(this.$refs.uload.files)
            let file = e.target.files[0]
            if (!/\.(gif|jpg|jpeg|png|bmp|GIF|JPG|PNG)$/.test(e.target.value)) {
              alert('图片类型必须是.gif,jpeg,jpg,png,bmp中的一种')
              return false
            }
            let oFReader = new FileReader();
            oFReader.readAsDataURL(file);
            //获取图片base64
            Loading.open()
            oFReader.onload = async (oFREvent) => {
              Loading.close();
              const noCropAvatar = oFREvent.target.result;
              this.$router.replace({name: 'avatarCrop', params: {noCropAvatar}});
            };
          }
        }
      },
      changeAvatar_info(){
        if (this.mode === 'edit') {
          if ($prod) {
            let onCameraSuccess = (noCropAvatar) => {
              Loading.close()
              this.$router.replace({
                name: 'avatarCrop',
                params: {noCropAvatar: `data:image/jpeg;base64,${noCropAvatar}`}
              });
            };
          let onCameraError = (message) => {
            Loading.close();
          };
            navigator.camera.getPicture(onCameraSuccess, onCameraError, {
              //质量
              quality: 100,
              //不允许编辑
              allowEdit: false,
              //获取图片转为base64
              destinationType: Camera.DestinationType.DATA_URL,
              //编码类型JPEG
              encodingType: Camera.EncodingType.JPEG,
              //只允许拍摄图片
              mediaType: Camera.MediaType.PICTURE,
              //按比例缩小图片宽度，单位px,kej
              targetWidth: 375
            });
            Loading.open()
          } else {
            alert('当前设备不支持')
          }
        }
      },
      deleteImg(index) {
        if (this.mode === 'edit') {
          this.info.identity_behind.splice(index, 1);
        }
      },
      deleteImg1(index) {
        if (this.mode === 'edit') {
          this.info.identity_front.splice(index, 1);
        }
      },
      loadImageUpload_photograph() {
        if (this.mode === 'edit') {
          let onCameraSuccess = (imageURI) => {
            this.info.identity_behind.length = 0;
            this.info.identity_behind.push(imageURI)
          };
          let onCameraError = (message) => {
          };
          if ($prod) {
            navigator.camera.getPicture(onCameraSuccess, onCameraError, {
              //质量
              quality: 100,
              //不允许编辑
              allowEdit: false,
              //获取图片转为base64
              destinationType: Camera.DestinationType.DATA_URL,
              //编码类型JPEG
              encodingType: Camera.EncodingType.JPEG,
              //只允许拍摄图片
              mediaType: Camera.MediaType.PICTURE,
              //按比例缩小图片宽度，单位px,kej
              targetWidth: 375
            });
          } else {
            alert('当前 设备不支持')
          }
        }
      },
      loadImageUpload_photograph1() {
        if (this.mode === 'edit') {
          let onCameraSuccess = (imageURI) => {
            this.info.identity_front.length = 0;
            this.info.identity_front.push(imageURI)
          };
          let onCameraError = (message) => {
          };
          if ($prod) {
            navigator.camera.getPicture(onCameraSuccess, onCameraError, {
              //质量
              quality: 100,
              //不允许编辑
              allowEdit: false,
              //获取图片转为base64
              destinationType: Camera.DestinationType.DATA_URL,
              //编码类型JPEG
              encodingType: Camera.EncodingType.JPEG,
              //只允许拍摄图片
              mediaType: Camera.MediaType.PICTURE,
              //按比例缩小图片宽度，单位px,kej
              targetWidth: 375
            });
          } else {
            alert('当前 设备不支持')
          }
        }
      },
      loadImageUpload_album() {
        if (this.mode === 'edit') {
          let onCameraSuccess = (imageURI) => {
            this.info.identity_behind.length = 0;
            this.info.identity_behind.push(imageURI)
          };
          let onCameraError = (message) => {
          };
          if ($prod) {
            navigator.camera.getPicture(onCameraSuccess, onCameraError, {
              //质量
              quality: 100,
              //不允许编辑
              allowEdit: false,
              //获取图片转为base64
              destinationType: Camera.DestinationType.DATA_URL,
              //编码类型JPEG
              encodingType: Camera.EncodingType.JPEG,
              //只允许拍摄图片
              mediaType: Camera.MediaType.PICTURE,
              //按比例缩小图片宽度，单位px,kej
              sourceType: Camera.PictureSourceType.SAVEDPHOTOALBUM,
              targetWidth: 375,

            });
          } else {
            alert('当前 设备不支持')
          }
        }
      },
      loadImageUpload_album1() {
        if (this.mode === 'edit') {
          let onCameraSuccess = (imageURI) => {
            this.info.identity_front.length = 0;
            this.info.identity_front.push(imageURI)
          };
          let onCameraError = (message) => {
          };
          if ($prod) {
            navigator.camera.getPicture(onCameraSuccess, onCameraError, {
              //质量
              quality: 100,
              //不允许编辑
              allowEdit: false,
              //获取图片转为base64
              destinationType: Camera.DestinationType.DATA_URL,
              //编码类型JPEG
              encodingType: Camera.EncodingType.JPEG,
              //只允许拍摄图片
              mediaType: Camera.MediaType.PICTURE,
              //按比例缩小图片宽度，单位px,kej
              sourceType: Camera.PictureSourceType.SAVEDPHOTOALBUM,
              targetWidth: 375,

            });
          } else {
            alert('当前 设备不支持')
          }
        }
      },
      isChecking() {
        return this.info.is_status === 1
      },
      isFaild() {
        return this.info.is_status === 3
      },
      validName(key) {
        if (!verify.isChinese(this.info[key]) || !verify.between(this.info[key], 2, 12)) {
          let message;
          if (key === 'name') message = '名字必须为中文且长度在2-12之间';
          else message = '紧急联系人姓名必须为中文且长度在2-12之间';
          this.$toast({message: message, position: 'middle'});
          return false;
        }
        if (!verify.mobile(this.info.other_tel)) {
          this.$toast({message: '紧急联系人电话格式错误', position: 'middle'});
          return false;
        }
        return true;
      }
    },
    computed: {
      text() {
        if (this.info.identity_behind.length === 0) {
          return '上传图片'
        }
        else if (this.info.identity_behind.length >= 0) {
          return '修改照片'
        }
      },
      text1() {
        if (this.info.identity_front.length === 0) {
          return '上传图片'
        }
        else if (this.info.identity_front.length >= 0) {
          return '修改照片'
        }
      },
      cont1() {
        return this.$store.cont = this.cont;
      },
      show(){
        if(this.mode==='readonly'){
         return false
        }else if(this.mode==='edit'){
          return true
        }
      },
      chose(){
        if(this.mode==='readonly'){
          return false
        }else if(this.mode==='edit'){
          return true
        }
      }
    },
    deactivated() {
      this.mode = 'readonly';
      this.sheetVisible = false;
      this.sheetVisible1= false;
    }
  }
</script>

<style lang="scss" scoped>
  @import "../../../assets/css/variables";
  @import '../../../assets/css/mixin';

  .ts-info {
    background: #F7F7F7;
  }

  .pending {
    @include sc(.28rem, white);
    text-align: center;
    padding: .23rem 0;
    &.checking {
      background-color: #C6C6C6;
    }
    &.faild {
      background-color: #7BC6FF;
    }
  }

  .profile-container {
    .avator {
      padding: .28rem 0;
      text-align: center;
      background-color: #ffffff;
      .pic {
        border-radius: 100%;
        @include wh(1.52rem, 1.52rem);
      }
      .update {
        @include sc(.3001rem, #909090);
        display: block;
        width: 76px;
        margin: .05rem auto 0;
      }
    }
  }
</style>
